﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace InCom.Core.TerminalSend.MappedFile
{
    using System.IO.MemoryMappedFiles;
    /// <summary>
    /// 文件映射扩展方法
    /// </summary>
    public static class MappedFileExtension
    {




        /// <summary>
        /// 读取字节
        /// </summary>
        /// <param name="offset">从0 开始的数据依稀量</param>
        /// <param name="length">要读取的数据长度</param>
        /// <returns></returns>
        public static byte[] Read(this MemoryMappedViewAccessor accessorView, long offset, long length)
        {
            long n = 0;
            byte[] buff = new byte[length];
            //循环读取
            for (long k = offset; k < offset + length; k++)
            {
                buff[n] = accessorView.ReadByte(k);
                n++;
            }
            return buff;
        }


        /// <summary>
        /// 写入一个字节数组
        /// </summary>
        /// <param name="bytes">要写入的文件数组</param>
        /// <param name="writeoffset">要写入文件起始位置</param>
        /// <returns>返回写入后的数据偏移量</returns>
        public static long Write(this MemoryMappedViewAccessor accessorView, byte[] bytes, long writeoffset)
        {
            long offset = writeoffset;
            //循环写入
            for (long i = 0; i < bytes.Length; i++)
            {
                accessorView.Write(offset, bytes[i]);
                offset++;
            }
            return offset;
        }
    }
}
